package com.geeaks.generator.controller;

import java.net.URL;
import java.util.ResourceBundle;
import org.apache.commons.lang3.StringUtils;
import com.geeaks.generator.model.TemplateBo;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

/**
 * @Description: 配置管理控制器
 * @author gaoxiang
 * @date 2019-04-13 11:23:17
 */
public class TemplateController extends BaseFXController {
	
	@FXML
	private TableView<TemplateBo> templateTableView;
	
	@FXML
	private TableColumn<TemplateBo, String> templateCodeField;
	
	@FXML
	private TableColumn<TemplateBo, String> templateNameField;
	
	private MainUIController mainUIController;
	
	/**
	 * @Fields templateCode : 选择的模板编码
	 */
	private String templateCode;
	
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		templateCodeField.setCellValueFactory(new PropertyValueFactory<>("templateCode"));
		templateNameField.setCellValueFactory(new PropertyValueFactory<>("templateName"));
		templateTableView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TemplateBo>() {
			@Override
			public void changed(ObservableValue<? extends TemplateBo> observable, TemplateBo oldValue, TemplateBo newValue) {
				templateCode = newValue.getTemplateCode();
			}
		});
	}
	
	@FXML
	public void ok() {
		ObservableList<TemplateBo> items = templateTableView.getItems();
		if (items != null && items.size() > 0) {
			items.stream().forEach(item -> {
				if (StringUtils.isNotEmpty(templateCode) && 
						item.getTemplateCode().equals(templateCode)) {
					mainUIController.setTemplateValue(item.getTemplateName());
					mainUIController.setTemplateBo(item);
				}
			});
		}
		getDialogStage().close();
	}
	
	@FXML
	public void cancel() {
		getDialogStage().close();
	}
	
	public void setTemplate(ObservableList<TemplateBo> columns) {
		templateTableView.setItems(columns);
	}
	
	public void setMainUIController(MainUIController mainUIController) {
		this.mainUIController = mainUIController;
	}
}
